package com.gitee.fantaros.web.fan.netcut.threading;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;

@Slf4j
public class DefaultSyncable<T> implements Syncable<T, String> {

    public static <T> DefaultSyncable<T> of(SyncExecutor<T, String> executor, Processable<String> processable) {
        DefaultSyncable<T> defaultSyncable = new DefaultSyncable<>();
        defaultSyncable.setExecutor(executor);
        defaultSyncable.setProcessable(processable);
        return defaultSyncable;
    }

    @Getter
    @Setter
    private Processable<String> processable;
    @Getter
    @Setter
    private Presentable<T> resultWrapper;
    @Getter
    @Setter
    private Presentable<Exception> anyException;
    @Getter
    @Setter
    private SyncExecutor<T, String> executor;

    private CountDownLatch countDownLatch;
    private boolean called;

    public DefaultSyncable() {
        this.called = false;
    }

    public DefaultSyncable(CountDownLatch countDownLatch) {
        this.called = false;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void markStarted() {
        this.called = true;
    }

    @Override
    public void markFinished(T t) {
        countDownLatch.countDown();
    }

    @Override
    public void setCountDownLatch(CountDownLatch countDownLatch) {
        if (this.called) {
            throw new IllegalStateException("无法给已执行的asyncable 设置 countDownLatch");
        }
        this.countDownLatch = countDownLatch;
    }
}
